package org.example.seckill.service;

import org.example.seckill.dao.OrderMapper;
import org.example.seckill.dao.ProductMapper;
import org.example.seckill.dao.pojo.Order;
import org.example.seckill.dao.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductService productService;

    @Autowired
    private SeckillService seckillService;

    /**
     * 标记订单为过期并添加库存
     * @param orderId
     */
    public void expireOrder(int orderId) {
        Order tOrder = orderMapper.findById(orderId);

        if (tOrder.getStatus() == Order.STATUS.NOT_PAY.ordinal()) {
            System.out.println("-------- expire order: " + tOrder.toString());
            tOrder.setStatus(Order.STATUS.EXPIRED.ordinal());
            orderMapper.update(tOrder);

            synchronized (this) {
                Product product = new Product();
                product.setId(1);
                productService.addInvenory(product, 1);
            }
        } else {
            System.out.println("+++ skip expire order: " + tOrder.toString());
        }
    }

    /**
     * 保存订单并减库存
     * @param userId
     * @param inventoryOrdinal
     */
    public Order createOrder(int userId, int inventoryOrdinal) {
        Order order = saveOrder(userId, inventoryOrdinal);
        Product product = new Product();
        product.setId(1);
        productService.deductInvenory(product, 1);
        return order;
    }

    /**
     * 保存订单
     */
    public Order saveOrder(int userId, int inventoryOrdinal) {
        Order order = new Order();
        order.setOrderNo(UUID.randomUUID() + String.format("%03d", inventoryOrdinal));
        order.setUserId(userId);
        order.setProductId(inventoryOrdinal);


        // 每10个秒杀订单中就有一个设置状态为未支付
        if (inventoryOrdinal % 10 == 0) {
            order.setStatus(Order.STATUS.NOT_PAY.ordinal());
        }
        // 正常支付
        else {
            order.setStatus(Order.STATUS.PAID.ordinal());
        }
        order.setCreatedAt(new Date());

        orderMapper.addOrder(order);
        return order;
    }


}
